package com.condroid;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;

/**
 * This class is a broadcast receiver for SMS.
 * this class need to be registered before 
 * receive the system notice.
 * @author JUN GAO
 * Condroid Summer CSD 2011 - KTH
 */
public class SMSReceiver extends BroadcastReceiver {
	private static SMSDealer smsDealer = null;

	@Override
	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub
		Bundle bundle = intent.getExtras();
		if (bundle != null) {
			Object[] pdus = (Object[]) bundle.get("pdus");
			SmsMessage[] msgs = new SmsMessage[pdus.length];
			for (int i = 0; i < pdus.length; i++)
				msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
			for (int i = 0; i < msgs.length; i++) {
//				 String smsToast = "New SMS received from "
//				 + msgs[i].getOriginatingAddress() + "\n'"
//				 + msgs[i].getMessageBody() + "'";
//				 Toast.makeText(context, smsToast, Toast.LENGTH_LONG).show();
				
				if (SmsCheck(msgs[i].getOriginatingAddress(),
						msgs[i].getMessageBody())) {
					if (smsDealer == null) {
						smsDealer = new SMSDealer();
						smsDealer.start();
						ConstantData.smsDealer = smsDealer;
					}
					smsDealer.deal(msgs[i].getOriginatingAddress(), msgs[i]
							.getMessageBody().substring(6).trim());
				}else
					Toast.makeText(context, "Not command SMS!", Toast.LENGTH_LONG).show();
			}
		}
	}

	private boolean SmsCheck(String phoneNo, String msg) {
		// TODO phone number and command format check

		return msg.startsWith(".SMSC:") && StdBySettings.checkAllowNo(phoneNo);
	}
}
